package com.cade.agriculturemall.view.shoppingCar.settlement;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseActivity;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.bean.NodeModel;
import com.cade.agriculturemall.bean.Remark;
import com.cade.agriculturemall.model.AddressEntity;
import com.cade.agriculturemall.model.Detail;
import com.cade.agriculturemall.model.GoodsDetailEntity;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.model.Ticket;
import com.cade.agriculturemall.utils.ConverUtil;
import com.cade.agriculturemall.view.shoppingCar.selecpaystatus.SelectPayStatusActivity;
import com.cade.agriculturemall.view.shoppingCar.settlement.TicketSelectDialog.TicketSelectDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;


import java.util.List;

public class SettlementActivity extends BaseActivity<SettlementContract.IPresenter> implements SettlementContract, SettlementContract.IView, SettlementAdapter.MyClickListener, TicketSelectDialog.DialogClick {
    private List<ShoppingCarsEntity> goodsSettlement = new ArrayList<>();
    private SettlementAdapter mAdapter = new SettlementAdapter(this, this);
    private int requestAddressCode = 1;
    public int change = 0;
    private float num = 0;
    private String type = "";
    private String addressId = "";
    private AddressEntity addressOrder = new AddressEntity();
    public int shoperNo = 0;
    private HashMap<String, NodeModel> hashMap = new HashMap<>();

    private Float orderCountPrice = 0.0f;
    private int goodsNum;
    private List<Ticket> tickets = new ArrayList<>();
    private TextView tvPayMoney;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        change = 0;
        setContentView(R.layout.activity_settlement);
        setupToolbar(true);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.settlement_address_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        TextView tvCountMoney = (TextView) findViewById(R.id.settlemet_tv_count_money);
        tvPayMoney = (TextView) findViewById(R.id.settlemet_tv_pay_money);
        tvCountMoney.setText("￥" + num + "");
        tvPayMoney.setText("实付：￥" + num);
    }

    @Override
    public void setupView() {

    }

    @Override
    public void setupEvent() {
        Button btnSubmit = (Button) findViewById(R.id.settlement_btn_submit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                skipNext();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (change == 0) {
            mPresenter.getFirstAddress();
        }
    }

    @Override
    public void setupData() {
        num = getIntent().getFloatExtra("num", 0);
        mPresenter.getFitTicketList(num);
        goodsSettlement = getIntent().getParcelableArrayListExtra("goodsSettlement");
        type = getIntent().getStringExtra("type");
        mPresenter.setType(type);
        goodsSettlement.size();
//        mPresenter.getFirstAddress();
//        地址数据
//          shoppingCars数据筛选分类整理

    }

    @Override
    public IPresenter setupPresenter() {
        return new SettlementPresenter(this);
    }

    @Override
    public void getList(List<AddressEntity> list) {
        if (list.size() == 0) {
            getAddress(null);// 无地址
        } else {
//  默认地址判断
            AddressEntity addressEntity = new AddressEntity();
            if (change == 0) {
                for (AddressEntity entity : list) {
                    if (entity.getIsfirst().equals("1")) {
                        addressEntity = entity;
                        break;
                    }
                }
            } else {
                addressEntity = list.get(0);
            }
            getAddress(addressEntity);
            addressOrder = addressEntity;
        }
    }

    @Override
    public void getTicket(List<Ticket> list) {
        if (list.size() != 0) {
            tickets = list;
        }
        init();
        mAdapter.notifyDataSetChanged();
    }

    public void init() {
        List<SettlementViewModel> models = new ArrayList<>();
        for (ShoppingCarsEntity entity : goodsSettlement) {
            orderCountPrice = 0.0f;
            goodsNum = 0;
            List<ShoppingCarsEntity> list = null;
            if (hashMap.containsKey(entity.getShoper())) {
                list = hashMap.get(entity.getShoper()).getShoppingCarsEntities();
            }
            if (list == null) {
                list = new ArrayList<>();
                NodeModel nodeModel = new NodeModel();
                nodeModel.setShoppingCarsEntities(list);
                hashMap.put(entity.getShoper(), nodeModel);
            }
            list.add(entity);
        }
        motifyModels(models);
        mAdapter.setModels(models);
    }

    public void motifyModels(List<SettlementViewModel> models) {
        for (String shoper : hashMap.keySet()) {
            orderCountPrice = 0.0f;
            goodsNum = 0;
            models.add(new SettlementViewModel(SettlementViewModel.TYPE_SJ,hashMap.get(shoper).getShoppingCarsEntities().get(0).getShoper()));
            shoperNo++;
            for (ShoppingCarsEntity entity : hashMap.get(shoper).getShoppingCarsEntities()) {
                SettlementViewModel viewModel = new SettlementViewModel(SettlementViewModel.TYPE_CP, entity);
                models.add(viewModel);
                if (TextUtils.isEmpty(type)) {
                    goodsNum += entity.getQuantitate();
                    orderCountPrice += entity.getQuantitate() * Float.parseFloat(entity.getPrice());
                } else {
                    goodsNum = 1;
                    orderCountPrice = Float.parseFloat(entity.getProId().getPriceNew());
                }
            }
            Detail detail = new Detail(orderCountPrice, goodsNum);
            models.add(new SettlementViewModel(SettlementViewModel.TYPE_SJ_FOOTER, detail));
        }
        if (tickets.size() != 0) {
            models.add(new SettlementViewModel(SettlementViewModel.TYPE_TICKET, null));
        }
        models.add(new SettlementViewModel(SettlementViewModel.TYPE_PAY, null));
    }

    @Override
    public void getAddress(AddressEntity entity) {
        if (entity == null) {
            monitor(entity, SettlementViewModel.TYPE_EMPTY, SettlementViewModel.TYPE_NO_FIRST, SettlementViewModel.TYPE_ADRESS);
        } else if (TextUtils.isEmpty(entity.getObjectId())) {
            monitor(entity, SettlementViewModel.TYPE_NO_FIRST, SettlementViewModel.TYPE_EMPTY, SettlementViewModel.TYPE_ADRESS);
        } else {
            monitor(entity, SettlementViewModel.TYPE_ADRESS, SettlementViewModel.TYPE_EMPTY, SettlementViewModel.TYPE_NO_FIRST);
        }
        mAdapter.notifyDataSetChanged();

    }

    public HashMap<String, NodeModel> getHashMap() {
        return hashMap;
    }

    /**
     * @param entity       添加的地址，entity状态区分指标：null---无地址   TextUtils.isEmpty(entity.getObjectId())---无默认地址   其它:
     * @param typeMine     添加的Type
     * @param clashTypeOne 冲突Type 需要移除
     * @param clashTypeTwo 冲突Type 需要移除
     */
    public void monitor(AddressEntity entity, int typeMine, int clashTypeOne, int clashTypeTwo) {
        List<SettlementViewModel> models = mAdapter.getModels();
        boolean exist = false;
        if (models != null && models.size() != 0) {
            for (SettlementViewModel model : models) {
                if (model.getType() == typeMine) {
                    exist = true;
                    model.setObject(entity);
                    break;
                }
                if (model.getType() == clashTypeOne || model.getType() == clashTypeTwo) {
                    models.remove(model);
                    break;
                }
            }
            if (!exist) {
                mAdapter.getModels().add(0, new SettlementViewModel(typeMine, entity));
            }
        }
    }

    //              ！！！！onActivityResult()发生在onResume()之前。
    //      选择地址后返回id 按addressId查找相关信息
    //      选择地址后返回id 按addressId查找相关信息
    int currentPosition = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestAddressCode == requestCode && data != null) {
            change = data.getIntExtra("change", 0);
            int a = change;
            addressId = data.getStringExtra("addressId");
            mPresenter.getRefreshAddress(addressId);
        }

    }


    OrderEntity entity = new OrderEntity();

    private boolean hadDone = false;

    private ArrayList<String> orderList = new ArrayList<>();
    private String dealNo = "";

    //      跳转至下一页面
    @Override
    public void skipNext() {
        if (!hadDone) {
            List<Remark> remarksList = mAdapter.getRemarkList();
            if (remarksList.size() != 0) {
                for (Remark remark : remarksList) {
                    if (hashMap.containsKey(remark.getShoper())) {
                        String detail = remark.getDetail();
                        hashMap.get(remark.getShoper()).setRemark(detail);
                    } else {
                        hashMap.get(remark.getShoper()).setRemark("hiihi");
                    }
                }
            }
            collectOrderInfo();
            dealNo = ConverUtil.getRandomDealNo();
            mPresenter.creatInOrder(dealNo, entity, hashMap);
            hadDone = true;
        }
        orderList = mPresenter.getOrderObjList();
        Intent intent = new Intent(this, SelectPayStatusActivity.class);
        if (!TextUtils.isEmpty(dealNo) && orderList.size() != 0) {
            if (!TextUtils.isEmpty(selectTicket.getObjectId())) {
                intent.putExtra("ticketId", selectTicket.getObjectId());
            }
            if (TextUtils.isEmpty(type)) {
                intent.putExtra("dealNo", dealNo);
            } else {
//                商品详情跳转
                Bundle bundle = new Bundle();
                bundle.putString("orderId", entity.getOrderId());
                List<GoodsDetailEntity> list = new ArrayList<>();
                list.add(goodsSettlement.get(0).getProId());
                bundle.putParcelableArrayList("goodsDetailEntity", (ArrayList<? extends Parcelable>) list);
                List<OrderEntity> list1 = new ArrayList<>();
                list1.add(entity);
                bundle.putParcelableArrayList("orderEntity", (ArrayList<? extends Parcelable>) list1);
//                bundle.putString("dealNo", dealNo);
                intent.putExtras(bundle);
            }
            intent.putStringArrayListExtra("orderList", orderList);//string 5a98f0a39f54545074163dff
            finish();
            startActivity(intent);
        } else {
            Toast.makeText(mActivity, "创建订单，请稍后再试", Toast.LENGTH_SHORT).show();
        }
        if (selectTicket.getObjectId() != null && !TextUtils.isEmpty(selectTicket.getObjectId())) {
            mPresenter.bingTicket(selectTicket.getObjectId());
        }
    }

    //  订单编号个数=商家个数  处理编号 1个
    public void collectOrderInfo() {
        String countPrice = num + "";
        String userId = mPresenter.getUserId();

        //获取当前时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("date=" + dateFormat.format(date.getTime()));//获取当前时间
        String orderSetttlementTime = dateFormat.format(date.getTime());
        Integer count = goodsSettlement.size();
        Integer payWay = null;
        if (mAdapter.pay_channel == "alipay") {
            payWay = 1;
        } else if (mAdapter.pay_channel == "wx") {
            payWay = 2;
        } else if (mAdapter.pay_channel == "bfd") {
            payWay = 3;
        }
        AddressEntity address = addressOrder;
        entity.setOrderPrice(countPrice);
        entity.setUserId(userId);
        entity.setOrderPriceCount(orderCountPrice + "");
        entity.setOrderSetttlementTime(orderSetttlementTime);
        entity.setProNum(count + "");
        entity.setPayWay(payWay);
        entity.setAddressId(address);
        entity.setOrderPayMoney(payMoney);
        entity.setTicketId(selectTicket.getObjectId());
    }

    private Ticket selectTicket = new Ticket();
    private String payMoney;

    private TicketSelectDialog dialog;

    @Override
    public void click(View v) {
        dialog = new TicketSelectDialog(this, this);
        dialog.getAdapter().setList(tickets);
        dialog.show();
        dialog.getAdapter().setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                selectTicket = tickets.get(position);
                payMoney = (num - Float.parseFloat(selectTicket.getMoney())) + "";
                tvPayMoney.setText("实付：￥" + payMoney);
                mAdapter.setSelectTv(selectTicket.getMoney());
                dialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void dialogClick(View view) {
        selectTicket = new Ticket();
        payMoney = "";
        tvPayMoney.setText("实付：" + num);
        mAdapter.setSelectTv(getResources().getString(R.string.dialog_ticket_btn));
        dialog.dismiss();
        mAdapter.notifyDataSetChanged();
    }
}
